package com.zhanghp.class016;

/**
 * @author zhanghp
 * @since 2024/3/2 15:59
 */
// 设计循环双端队列
// 测试链接 : https://leetcode.cn/problems/design-circular-deque/
public class CircularDeque {
    class MyCircularDeque {

        public int[] deque;

        public int r, l, size, limit;

        public MyCircularDeque(int k) {
            this.deque = new int[k];
            r = l = size = 0;
            limit = k;
        }

        public boolean insertFront(int value) {
            if (isFull()) {
                return false;
            } else {
                if (isEmpty()) {
                    // 删除后，l,r不在0，所以重新置空
                    // 也可在删除头/尾时，多加个判断，判断size是否只有1个，是的话，l=r=0
                    l = r = 0;
                    deque[l] = value;
                } else {
                    l = l == 0 ? limit - 1 : l - 1;
                    deque[l] = value;
                }
                size++;
                return true;
            }
        }

        public boolean insertLast(int value) {
            if (isFull()) {
                return false;
            } else {
                if (isEmpty()) {
                    // 删除后，l,r不在0，所以重新置空
                    // 也可在删除头/尾时，多加个判断，判断size是否只有1个，是的话，l=r=0
                    l = r = 0;
                    deque[l] = value;
                } else {
                    r = r == limit - 1 ? 0 : r + 1;
                    deque[r] = value;
                }
                size++;
                return true;
            }
        }

        public boolean deleteFront() {
            if (isEmpty()) {
                return false;
            } else {
                l = l == limit - 1 ? 0 : l + 1;
                size--;
                return true;
            }
        }

        public boolean deleteLast() {
            if (isEmpty()) {
                return false;
            } else {
                r = r == 0 ? limit - 1 : r - 1;
                size--;
                return true;
            }
        }

        public int getFront() {
            return isEmpty() ? -1 : deque[l];
        }

        public int getRear() {
            return isEmpty() ? -1 : deque[r];
        }

        public boolean isEmpty() {
            return size == 0;
        }

        public boolean isFull() {
            return size == limit;
        }
    }
}
